import { orderList, freeData } from '../utils/mockdata'

import { apiUrl, wsType, wsUrl, latRange, lngRange,orderLatRange,orderLngRange, pageSize, duration } from '../config/config'
import { showLoading, showToast } from './promiseFns'

var userInfo = null;

function postUserInfo(data) {

    return new Promise((resolve, reject) => {
        var userName = getAppUserInfo().nickName
        wx.request({
            url: apiUrl + '/postData?id=' + userName,
            data: {
                name: data.name,
                phone: data.phone,
                idcard: data.idcard,
                departure: data.departure,
                dest: data.dest,
                departurePoint: {
                    lat: data.departurePoint.lat,
                    lng: data.departurePoint.lng
                }
            },
            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: function(res) {
                resolve(res);
            },
            fail: function() {
                reject(false)
            },
            complete: function() {
                reject(false)
            }
        })
    })

}

function getMyOrder() {

    return new Promise((resolve, reject) => {
        var userName = getAppUserInfo().nickName
        wx.request({
            url: apiUrl + '/my?id=' + userName,
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: (res) => {
                resolve(res)
            },
            fail: function() {
                reject('请求我的信息失败')
            },
            complete: function() {}
        })
    })
}

function getAppUserInfo() {
    if (userInfo) {
        return userInfo
    }
    userInfo = getApp().userInfo;
    return userInfo;
}

function cancelOrder() {

    return new Promise((resolve, reject) => {

        var userName = getAppUserInfo().nickName

        wx.request({
            url: apiUrl + '/cancel?id=' + userName,
            method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: function(res) {
                resolve(res)
            },
            fail: function() {
                reject('取消出行错误')
            }
        })

    })

}

function getOrders() {
    return new Promise((resolve, reject) => {
        var userName = getAppUserInfo().nickName
        resolve(orderList)
        wx.request({
            url: apiUrl + '/orders',
            method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
            success: (res) => {
                resolve(orderList)
            },
            fail: function() {
                reject('请求我的信息失败')
            },
            complete: function() {
                // 
                reject(false)
            }
        })
    })
}

// var seqnum = 0;

function getSendSocketData(centerPos, app, wsTypeName) {

    var pointData,
        paramData,lngR,latR;

    if(wsTypeName == wsType.freeBarrier){
        lngR = lngRange;
        latR = latRange;
    }else{
        lngR = orderLngRange;
        latR = orderLatRange;
    }

    var ref_lng = parseFloat(centerPos.longitude.toFixed(6));
    var ref_lat = parseFloat(centerPos.latitude.toFixed(6));

    var from_lng = parseFloat((ref_lng - lngR).toFixed(6));
    var to_lng = parseFloat((ref_lng + lngR).toFixed(6));

    var from_lat = parseFloat((ref_lat - latR).toFixed(6));
    var to_lat = parseFloat((ref_lat + latR).toFixed(6));

    // seqnum += 1;
    app.increaseSeq();

    pointData = {
        "from_lng": from_lng,
        "to_lng": to_lng,
        "from_lat": from_lat,
        "to_lat": to_lat,
        "ref_lng": ref_lng,
        "ref_lat": ref_lat,
        "page_no": 1,
        "page_size": pageSize
    }

    if (wsTypeName == wsType.freeBarrier) {

        paramData = {
            "service": "map",
            "api": "barrier-free",
            "version": 1,
            "seqnum": app.seqnum,
            "params": pointData
        }

    } else {

        pointData.duration = duration ;

        paramData = {
            "service": "service",
            "api": "service-request",
            "version": 1,
            "seqnum": app.seqnum,
            "params": pointData
        }

    }

    return paramData

}

var isSocketOpen = false;

function connectAndOpenSocket() {

    return new Promise((resolve, reject) => {

        if (!isSocketOpen) {

            // showLoading('connect');

            wx.connectSocket({
                url: wsUrl
            })

            wx.onSocketOpen(function(res) {
                
                isSocketOpen = true;
                wx.hideLoading();
                resolve(true)
            })

        } else {

            resolve(true);

        }

    })

}

function closeSocket() {

    return new Promise((resolve, reject) => {
        if (isSocketOpen) {
            wx.closeSocket();
            wx.onSocketClose(function(res) {
                isSocketOpen = false;
                resolve(true)
            })
        }else{
            resolve(true)
        }
    })

}


function sendPosDataToSocket(centerPos, app, wsTypeName) {

    var stringData = JSON.stringify(getSendSocketData(centerPos, app, wsTypeName))

    return connectAndOpenSocket().then(connected => {
        return getData()
    })

    function getData() {

        return new Promise((resolve, reject) => {

            if (isSocketOpen) {
                
                wx.sendSocketMessage({
                    data: stringData,
                        success: function(res) {
                        
                        resolve(true)
                    },
                    fail: function() {
                        // showToast('连接服务器失败:socket1','','/resources/images/error3.png')
                        // closeSocket()
                        
                        isSocketOpen = false;
                        reject('fail at socket')
                    },
                    complete:function(){
                        
                    }
                })
            } else {

                reject('socket is not open');

            }

        })
    }

}


/**
 * 设置查询参数
 * @param {String} api 
 * @param {Object} params 
 * @returns 
 */
function setParams(api, params) {
    return {
        "service": "map",
        "api": api,
        "version": 1,
        "params": params
    }
}

const coordCatParams = setParams('queryCoordinateCat', {});

const freeBarrierTypesParams = setParams('queryBarrierFreeFac', {});

function dataQuery(paramsData) {

    return () => {

        return new Promise((resolve, reject) => {

            wx.request({
                url: apiUrl,
                data: paramsData,
                method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
                // header: {}, // 设置请求的 header
                success: function(res) {

                    // resolve(res.data.result)

                    if (res.data.code == 0) {
                        resolve(res);
                    } else {
                        reject(res.data.msg);
                    }
                },
                fail: function() {

                    reject('服务中断,请重新再试')
                }

            })

        })
    }

}

var app = null;

function get_app() {
    if (!app) {
        app = getApp()
    }
    return app
}

const getCoordinateCat = dataQuery(coordCatParams);

const getFreeBarrierType = dataQuery(freeBarrierTypesParams);

module.exports = {
    postUserInfo: postUserInfo,
    getMyOrder: getMyOrder,
    cancelOrder: cancelOrder,
    getOrders: getOrders,
    sendPosDataToSocket: sendPosDataToSocket,
    getCoordinateCat: getCoordinateCat,
    getFreeBarrierType: getFreeBarrierType,
    dataQuery: dataQuery,
    setParams: setParams,
    closeSocket: closeSocket
}